package com.pay.cloud.fragment;

import com.pay.cloud.BindState;
import com.pay.cloud.DataFactory;
import com.pay.cloud.cpay.MyCloudPay;
import com.tencent.cloudpay.CloudPay;

import static com.pay.cloud.fragment.TipFragment.TipType.ERROR;
import static com.pay.cloud.fragment.TipFragment.TipType.FAIL;
import static com.pay.cloud.fragment.TipFragment.TipType.SUCCESS;
import static com.pay.cloud.fragment.TipFragment.TipType.WAIT;

public class DomainFragment extends TipHorizontalFragment implements BindState {
    private static final String[] domains = {"https://pay.qcloud.com", "https://sz.pay.qcloud.com", "https://sh.pay.qcloud.com", "https://tj.pay.qcloud.com"};
    private String domain;
    private int endIndex = -1;
    private int startIndex = 0;

    public DomainFragment(String domain) {
        super(WAIT, domain);
        this.domain = domain;
    }

    public DomainFragment(int i) {
        super(WAIT, domains[i]);
        this.startIndex = i;
        if (i == 0) {
            this.endIndex = domains.length - 1;
        } else {
            this.endIndex = i - 1;
        }
    }

    @Override
    public void execute() throws Exception {
        setTextSize(30f);
        if (endIndex == -1) {
            check();
        } else {
            check(startIndex);
        }
    }

    @Override
    public boolean useNetwork() {
        return true;
    }

    @Override
    public void onError(String msg) {
        onChange(ERROR, msg);
    }

    private void check(int index) {
        domain = domains[index];
        onChange(WAIT, domain);
        try {
            int state = MyCloudPay.getInstance(getActivity()).ping(domain);
            if (state != 0) {
                throw new Exception();
            }
            DataFactory.getDataStore().setServerUrl(domain);
            CloudPay.getInstance().setDomain(domain);
            onChange(SUCCESS, domain);
            speak("域名切换成功");
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {
            }
            if (endIndex == index) {
                onChange(ERROR, "无可用域名");
                speak("无可用域名");
                return;
            }
            if ((index + 1) < domains.length) {
                check(index + 1);
            } else {
                check(0);
            }
        }
    }

    private void check() {
        int state = MyCloudPay.getInstance(getActivity()).ping(domain);
        if (state == 0) {
            onChange(SUCCESS, domain);
        } else {
            onChange(FAIL, domain);
            speak("当前域名不可用");
        }
    }
}
